package com.android.settings.audio.peq.peq;

import android.content.Context;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;

import com.android.settings.R;
import com.android.settings.audio.peq.peq.ui.dialog.CommanDialog;


public class QrEditTextDialog {
    private CommanDialog mDialog;
    private EditText etValue;
    private ImageButton imgb_show_password_switch;

    private Context mContext;

    private String title;
    private ConfirmListener mSubmitListener;
    private View.OnClickListener mCancelListener;

    public QrEditTextDialog(Context context) {
        this.mContext = context;
        initDialog();
    }

    public QrEditTextDialog(Context context, String title) {
        this.mContext = context;
        this.title = title;
        initDialog();
    }

    private void initDialog() {
        if (mDialog == null) {
            mDialog = new CommanDialog(mContext, R.style.peqMyDialogStyle, CommanDialog.STYLE_3_HASTITLE_HASTWOBUTTON);
            mDialog.addView(R.layout.peq_dialog_edittext_qr);
            View contentView = mDialog.getContentView();

            etValue = contentView.findViewById(R.id.et_value);

            imgb_show_password_switch = contentView.findViewById(R.id.imgb_show_password_switch);
            if (title != null) {
                mDialog.titleTextView.setText(title);
            }
            mDialog.setCanceledOnTouchOutside(true);

            mDialog.ok.setOnClickListener(v -> onOk());
            mDialog.cancle.setOnClickListener(v -> onCancel());

        }

        etValue.setText("");
    }

    public CommanDialog getDialog() {
        return mDialog;
    }

    public void showDialog(String value, ConfirmListener submitListener) {
        mSubmitListener = submitListener;
        if (mDialog != null) {
            etValue.setText(value);
            if (!mDialog.isShowing()) {
                mDialog.show();
            }
            android.os.Handler handler = mDialog.getContentView().getHandler();
            if (handler != null) handler.postDelayed(() -> {
                etValue.setSelection(etValue.getText().length());
                etValue.requestFocus();
                //AudioOptionTool.showKeyboard(etValue, mDialog);
            }, 100);
        }
    }

    private void onOk() {
        String value = etValue.getText().toString().trim();
        if (mSubmitListener != null) {
            boolean isOk = mSubmitListener.onSubmit(value);
            if (!isOk) {
                return;
            }
        }
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.cancel();
        }
    }

    private void onCancel() {
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.cancel();
        }
        etValue.setText("");
    }

    public interface ConfirmListener {
        boolean onSubmit(String value);
    }
}
